package com.mti.threadhandle;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.mti.component.snowflake.KeyWorker;
import com.mti.dao.model.*;
import com.mti.enums.ReceiveFlag;
import com.mti.jwt.AccountBo;
import com.mti.service.*;
import com.mti.service.impl.SpecialPersonComponent;
import com.mti.service.impl.SpecialPersonServiceImpl;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.server.ServerWebExchange;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.Lock;

/**
 * @Classname SaveLfZdryBaseHandle
 * @Description TODO
 * @Date 2020/4/8 20:09
 * @Created by duchaof
 * @Version 1.0
 */
@AllArgsConstructor
@Slf4j
@Data
public class SaveLfZdryBaseHandle implements Runnable {

    private SpecialPersonServiceImpl specialPersonService;

    private LfZdryBaseService lfZdryBaseService;

    private KmZdryTypeService kmZdryTypeService;

    private KmZdryAssistService kmZdryAssistService;

    private KmZdryHomeService kmZdryHomeService;

    private LfZdryExportDataService lfZdryExportDataService;

    private TKmProRightService  tKmProRightService;

    private LfZdryHistoryLogService lfZdryHistoryLogService;

    private SpecialPersonComponent specialPersonComponent;

    private LfZdryExportDataEntity zdry;

    private AccountBo bo;

    ServerWebExchange exchange;

    private Lock lock;
    


    @Override
    public void run() {
        //System.out.println("======当前线程名称为：" + Thread.currentThread().getName() + "======");
        lock.lock();
        try {
            //  当数据库有某个重点人员时（身份证号及姓名一致），导入或者新增时，新信息做辅助信息。
            //  若身份证号一致，而姓名/户籍地不同，报错返回并提示原因。
            LfZdryBaseEntity lfZdryBase = lfZdryBaseService.getOne(new QueryWrapper<LfZdryBaseEntity>()
                    .eq("sfzh", zdry.getSfzh()).last("limit 1"));
            if (null == lfZdryBase) { // 添加
                LfZdryBaseEntity lfZdry = zdry.transToZdryBase();
                lfZdry.setCreateTimex(new Date());
                lfZdry.setUpdateTimex(new Date());
                lfZdry.setId(String.valueOf(KeyWorker.nextId()));
                //如果现住址省 现住址市 现住址县 县住址(新增时)
                if(null == zdry.getXzzs()&& null == zdry.getXzzss() && null == zdry.getXzzx() && null == zdry.getXzz()) {
                    zdry.setXzz(zdry.getHjd());
                    zdry.setXzzs(zdry.getHjs());
                    zdry.setXzzss(zdry.getHjss());
                    zdry.setXzzx(zdry.getHjx());

                    lfZdry.setXzz(zdry.getHjd());
                    lfZdry.setXzzs(zdry.getHjs());
                    lfZdry.setXzzss(zdry.getHjss());
                    lfZdry.setXzzx(zdry.getHjx());
                }
                //判断管控民警是否被分配
                if(zdry.getGkmj() != null && !"".equals(zdry.getGkmj())){
                    lfZdry.setReceiveFlag(ReceiveFlag.RECEIVED.getStatus());
                }else {
                    lfZdry.setReceiveFlag(ReceiveFlag.NOT_RECEIVED.getStatus());
                }
                specialPersonService.arrangeZdryBaseData(lfZdry,zdry);

                boolean addResult = lfZdryBaseService.save(lfZdry);
                //lfZdryBaseService.operatLog("新增", bo, lfZdry, "导入重点人员","数据导入",exchange);
                if (addResult) {
                    // 插入t_km_zdry_type
                    KmZdryTypeEntity zt = zdry.transToKmZdryType(lfZdry.getId());
                    zt.setId(String.valueOf(KeyWorker.nextId()));
                    specialPersonService.arrangeZdryTypeData(zt);
                    zt.setZzjz(1);
                    kmZdryTypeService.save(zt);
                    // 插入 t_km_zdry_assist
                    List<KmZdryAssistEntity> assistEntities = zdry.transToKmZdryAssist(lfZdry.getId());
                    for (KmZdryAssistEntity assistEntity : assistEntities) {
                        assistEntity.setId(String.valueOf(KeyWorker.nextId()));
                        kmZdryAssistService.save(assistEntity);
                    }


                    if(!(null == zdry.getXzzs() && null == zdry.getXzzss() && null == zdry.getXzzx() && null == zdry.getXzz())){
                        // 插入t_km_zdry_home
                        KmZdryHomeEntity home = zdry.transToKmZdryHome(lfZdry.getId());
                        home.setX(lfZdry.getX());
                        home.setY(lfZdry.getY());
                        home.setZjzdbj(1);
                        kmZdryHomeService.save(home);
                    }

                    if(null != zdry.getAppeal() && zdry.getAppeal().length()>0){
                        // 插入t_km_pro
                        TKmProEntity pro = zdry.transToKmPro(lfZdry.getId());
                        tKmProRightService.save(pro);
                        // 插入 t_lf_zdry_history_log
                       // LfZdryHistoryLogEntity log = zdry.transToLfZdryHistoryLog(bo,lfZdry.getId());
                       // lfZdryHistoryLogService.save(log);
                    }
                }
                lfZdryExportDataService.updateExportDataSign(lfZdry.getSfzh());
            } else { // 编辑
                if(lfZdryBase.getXm().equals(zdry.getXm())){ //身份证相同，姓名相同 编辑
                    LfZdryBaseEntity lfZdry = zdry.transToZdryBase();
                    lfZdry.setUpdateTimex(new Date());
                    specialPersonService.arrangeZdryBaseData(lfZdry,null);
                    //lfZdryBaseService.updateZdryBySfzh(lfZdry);
                    lfZdry.setXzzs(null);
                    lfZdry.setXzzss(null);
                    lfZdry.setXzzx(null);
                    lfZdry.setXzz(null);
                    lfZdryBaseService.update(lfZdry, new UpdateWrapper<LfZdryBaseEntity>().lambda().eq(LfZdryBaseEntity::getSfzh, lfZdry.getSfzh()));


                    KmZdryTypeEntity zt = zdry.transToKmZdryType(lfZdryBase.getId());
                    Integer kmZdryTypeCount = kmZdryTypeService.count(new QueryWrapper<KmZdryTypeEntity>()
                            .lambda().eq(KmZdryTypeEntity::getRylb,zt.getRylb()).eq(KmZdryTypeEntity::getXl,zt.getXl())
                            .eq(KmZdryTypeEntity::getZdryId,lfZdryBase.getId()));
                    if(kmZdryTypeCount ==0){
                        // 打日志用
                        List<KmZdryTypeEntity> typeEntities = new ArrayList<>();
                        typeEntities.add(new KmZdryTypeEntity(zt.getId(),zt.getRylb(),zt.getRylbCode(),zt.getZrbm(),zt.getXl(),zt.getXlCode(),zt.getZzjz(),
                                zt.getZdryId()));
                        lfZdry.setTypeList(typeEntities);

                        zt.setId(String.valueOf(KeyWorker.nextId()));
                        specialPersonService.arrangeZdryTypeData(zt);
                        kmZdryTypeService.save(zt);
                    }
                    List<KmZdryAssistEntity> assistEntities = zdry.transToKmZdryAssist(lfZdryBase.getId());
                    List<KmZdryAssistEntity> assistes = new ArrayList<>();
                    for (KmZdryAssistEntity assistEntity : assistEntities) {
                        Integer assistCount = kmZdryAssistService.count(new QueryWrapper<KmZdryAssistEntity>()
                                .lambda().eq(KmZdryAssistEntity::getInfoValue,assistEntity.getInfoValue())
                                .eq(KmZdryAssistEntity::getInfoType,assistEntity.getInfoType())
                                .eq(KmZdryAssistEntity::getZdryId,lfZdryBase.getId()));
                        if(assistCount == 0){
                            //打印日志
                            assistes.add(new KmZdryAssistEntity(assistEntity.getId(),assistEntity.getZdryId(),assistEntity.getInfoType(),assistEntity.getInfoValue(),
                                    assistEntity.getIndex()));

                            assistEntity.setId(String.valueOf(KeyWorker.nextId()));
                            kmZdryAssistService.save(assistEntity);
                        }
                    }
                    lfZdry.setAssistList(assistes);


                    if(!(null == zdry.getXzzs() && null == zdry.getXzzss() && null == zdry.getXzzx() && null == zdry.getXzz())){
                        KmZdryHomeEntity home = zdry.transToKmZdryHome(lfZdryBase.getId());

                        QueryWrapper<KmZdryHomeEntity> queryWrapper = new QueryWrapper<>();
                        queryWrapper.lambda().eq(KmZdryHomeEntity::getZdryId,lfZdryBase.getId());
                        if(null != zdry.getXzzs() && zdry.getXzzs().length()>0)
                            queryWrapper.lambda().eq(KmZdryHomeEntity::getXzzs,home.getXzzs());
                        if(null != zdry.getXzzss() && zdry.getXzzss().length()>0 )
                            queryWrapper.lambda().eq(KmZdryHomeEntity::getXzzss,home.getXzzss());
                        if(null != zdry.getXzzx() && zdry.getXzzx().length()>0)
                            queryWrapper.lambda().eq(KmZdryHomeEntity::getXzzx,home.getXzzx());
                        if(null != zdry.getXzz() && zdry.getXzz().length()>0)
                            queryWrapper.lambda().eq(KmZdryHomeEntity::getXzz,home.getXzz());

                        Integer homeCount = kmZdryHomeService.count(queryWrapper);
                        if(homeCount == 0){

                            // 打印日志使用
                            List<KmZdryHomeEntity> homeEntities = new ArrayList<>();
                            homeEntities.add(new KmZdryHomeEntity(home.getId(),home.getZdryId(),home.getXzzs(),home.getXzzss(),home.getXzzx(),home.getXzz(),
                                    home.getIndex(),home.getX(),home.getY(),home.getZjzdbj()));

                            home.setId(String.valueOf(KeyWorker.nextId()));
                            home.setX(lfZdryBase.getX());
                            home.setY(lfZdryBase.getY());
                            lfZdry.setJzdList(homeEntities);
                            kmZdryHomeService.save(home);
                        }
                    }

                    lfZdry.setId(lfZdryBase.getId());
                    String logRecord = specialPersonComponent.getModifyInfo(lfZdry,lfZdryBase);
                    //空字符替换
                    if(logRecord.contains("【】")) {
                        logRecord = logRecord.replaceAll("【】", "【空】");
                    }

                    if(null != zdry.getAppeal() && zdry.getAppeal().length()>0){
                        // 插入t_km_pro
                        TKmProEntity pro = zdry.transToKmPro(lfZdryBase.getId());
                        tKmProRightService.save(pro);
                        // 插入 t_lf_zdry_history_log
                        LfZdryHistoryLogEntity log = zdry.transToLfZdryHistoryLog(bo,lfZdryBase.getId());
                        lfZdryHistoryLogService.save(log);
                    }
                  //  lfZdryBaseService.operatLog("修改", bo, lfZdry, logRecord,"数据导入时编辑",exchange) ;
                    lfZdryExportDataService.updateExportDataSign(lfZdryBase.getSfzh());
                }
            }
        } catch (Exception e) {
            log.error("添加数据时发生异常：" + e.getMessage());
            lfZdryBaseService.deleteZdry(zdry.getId(),exchange);
        }finally {
            lock.unlock();
        }
    }
}
